//
//  PainterTextView.m
//  ChartRefactor
//
//  Created by CaoJun on 15/3/17.
//  Copyright (c) 2015年 CaoJun. All rights reserved.
//

#import "PainterTextView.h"

using namespace ytx;

@implementation PainterTextView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.dataIndexForTopSideText = nil;
    }
    return self;
}

- (void) drawTopSideTextWithX:(CGFloat) x
{
    if (![self hasData]){
        return;
    }
    self.dataIndexForTopSideText = @(self.indexPosition->getDataIndexByPX(x));
    [self setNeedsDisplay];
}

- (void) drawTopSideText:(NSNumber *) dataIndexForTopSideText
{
    self.dataIndexForTopSideText = dataIndexForTopSideText;
    [self setNeedsDisplay];
}

- (void) resetTopSideText
{
    self.dataIndexForTopSideText = nil;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)cgrect
{
    if (![self hasData]){
        return;
    }
    
    // Drawing code.
    //获得处理的上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    ChartCanvas * ctx = [ChartCanvas new];
    ctx.context = context;
    ctx.bounds = self.bounds;
    
    ViewModelIndexPosition * indexPosition = self.indexPosition;
    
    PainterText * painter = (PainterText *) self.painter;
    
    CGRect leftSideTextRect = [painter drawLeftSideText:cgrect withContext:ctx withViewModelIndexPosition:indexPosition];
    [painter drawRightSideText:cgrect withContext:ctx withViewModelIndexPosition:indexPosition];
    
    int dataIndex;
    
    if (self.dataIndexForTopSideText == nil) {
        dataIndex = indexPosition->getEndDataIndexInRange();
    }
    else{
        dataIndex = [self.dataIndexForTopSideText intValue];
    }
    
    [painter drawTopSideText:cgrect withContext:ctx withViewModelIndexPosition:indexPosition withDataIndex:dataIndex withLeftSideTextRect:leftSideTextRect];
    
    [painter drawBottomSideText:cgrect withContext:ctx withViewModelIndexPosition:indexPosition ];
    
}


@end
